﻿﻿using SearchAlgorithms.extention;
using System;
using System.Collections.Generic;
using System.Threading.Tasks.Dataflow;

namespace SearchAlgorithms.Services
{
    public class CompareBlock
    {

        public Action<(bool, int)> DataArrived;
        public ActionBlock<Tuple<byte[], byte[]>> compareBlock;
        public JoinBlock<byte[], byte[]> jb = new JoinBlock<byte[], byte[]>();
        private int framenumber = 0;
        public CompareBlock(string CompareMethod)
        {
            // 初始化 compareBlock
            compareBlock = new ActionBlock<Tuple<byte[], byte[]>>((input) =>
            {
                bool result = false;
                if (CompareMethod == "Comparison")
                {
                    framenumber++;
                    result = input.Item1.AsSpan().Comparison(input.Item2.AsSpan());//用比较算法对比两个帧
                }
                else if (CompareMethod == "CompareWithSequence")
                {
                    framenumber++;
                    result = input.Item1.AsSpan().CompareWithSequence(input.Item2.AsSpan());//用比较算法对比两个帧  
                }
                DataArrived?.Invoke((result, framenumber));

            }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1 }); // 确保顺序执行
            // 链接 jb 和 compareBlock
            jb.LinkTo(compareBlock, new DataflowLinkOptions { PropagateCompletion = true });
        }

        public void Enqueue_1(byte[] input1)
        {
            jb.Target1.Post(input1); // 文件1的数据帧
        }

        public void Enqueue_2(byte[] input2)
        {
            jb.Target2.Post(input2); // 文件2的数据帧
        }
    }
}